package com.shensi.adminCollect.controller.station;


import com.alibaba.fastjson.JSONObject;
import com.shensi.adminCollect.common.annotation.Excel;
import com.shensi.adminCollect.common.constant.HttpStatus;
import com.shensi.common.core.controller.BaseController;
import com.shensi.common.core.domain.AjaxResult;
import com.shensi.common.core.page.PageDomain;
import com.shensi.common.core.page.TableDataInfo;
import com.shensi.common.core.page.TableSupport;
import com.shensi.adminCollect.common.utils.poi.ExcelUtil;
import com.shensi.adminCollect.domain.station.Commodity;
import com.shensi.adminCollect.domain.station.WarehouseBatch;
import com.shensi.adminCollect.domain.station.WarehouseDetails;
import com.shensi.adminCollect.domain.station.vo.CommodityExportErrorVo;
import com.shensi.adminCollect.service.station.CommodityService;
import com.shensi.adminCollect.service.station.WarehouseBatchService;
import com.shensi.adminCollect.service.station.WarehouseDetailsService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * 入库详情表
 * */

@RestController
@RequestMapping
@Slf4j
public class WarehouseDetailsController extends BaseController {

    @Autowired
    private WarehouseDetailsService warehouseService;

    @Autowired
    private WarehouseBatchService warehouseBatchService;

    @Autowired
    private CommodityService commodityService;


    @PostMapping("/warehouse/add")
    @ApiOperation(value = "新增入库单", httpMethod = "POST")
    public AjaxResult addWarehouse(@RequestBody WarehouseDetails warehouse){
        if(Objects.isNull(warehouse) || Objects.isNull(warehouse.getStationId())){
            return AjaxResult.error("请求参数异常");
        }
        if(CollectionUtils.isEmpty(warehouse.getWarehouseList())){
            return AjaxResult.error("没有入库单");
        }
        warehouseService.addWarehouse(warehouse);

        return AjaxResult.success();
    }

    @PostMapping("/warehouse/addList")
    @ApiOperation(value = "新增入库单列表", httpMethod = "POST")
    public AjaxResult addWarehouseList(@RequestBody List<Commodity> commodityList){
        if(CollectionUtils.isEmpty(commodityList)){
            return AjaxResult.error("没有入库单");
        }
        warehouseService.addWarehouseList(commodityList);

        return AjaxResult.success();
    }


    @GetMapping("/warehouse/list")
    @ApiOperation(value = "查看入库详情单", httpMethod = "GET")
    public AjaxResult selectWarehouseList(@RequestParam("batchId") Long batchId){
        if(Objects.isNull(batchId)){
            return AjaxResult.error("请求参数异常");
        }
        log.info("selectWarehouseList 查询入库请求参数：[{}]",batchId);
        List<WarehouseDetails> warehouseList = warehouseService.selectWarehouseList(batchId);
        log.info("selectWarehouseList 查询入库返回结果：[{}]",warehouseList.size());
        return AjaxResult.success(warehouseList);
    }

    @PostMapping ("/warehouse/batch/list")
    @ApiOperation(value = "查看入库批次列表", httpMethod = "POST")
    public TableDataInfo selectWarehouseBatchList(@RequestBody WarehouseBatch warehouseBatch){
        if(Objects.isNull(warehouseBatch) || Objects.isNull(warehouseBatch.getPageNum())
                || Objects.isNull(warehouseBatch.getPageSize())){
            TableDataInfo rspData = new TableDataInfo();
            rspData.setCode(HttpStatus.ERROR);
            rspData.setMsg("请求参数异常");
            rspData.setRows(null);
            rspData.setTotal(0);
            return rspData;
        }
        log.info("selectWarehouseBatchList 查看入库批次列表：[{}]", JSONObject.toJSONString(warehouseBatch));
        PageDomain pageDomain = TableSupport.buildPageRequest();
        pageDomain.setPageNum(warehouseBatch.getPageNum());
        pageDomain.setPageSize(warehouseBatch.getPageSize());
        startPage(pageDomain);
        List<WarehouseBatch> warehouseBatches = warehouseBatchService.selectWarehouseBatchList(warehouseBatch);
        return getDataTable(warehouseBatches);
    }

    /**
     * 库存管理
     * */
    @PostMapping("/warehouse/manage")
    @ApiOperation(value = "库存管理列表", httpMethod = "POST")
    public TableDataInfo selectWarehouseManage(@RequestBody Commodity commodity){
        if(Objects.isNull(commodity) || Objects.isNull(commodity.getPageNum())
                || Objects.isNull(commodity.getPageSize())){
            TableDataInfo rspData = new TableDataInfo();
            rspData.setCode(HttpStatus.ERROR);
            rspData.setMsg("请求参数异常");
            rspData.setRows(null);
            rspData.setTotal(0);
            return rspData;
        }
        logger.info("库存管理列表,请求参数：[{}]", JSONObject.toJSONString(commodity));
        PageDomain pageDomain = TableSupport.buildPageRequest();
        pageDomain.setPageNum(commodity.getPageNum());
        pageDomain.setPageSize(commodity.getPageSize());
        startPage(pageDomain);
        List<Commodity> commodityList = commodityService.selectCommodityList(commodity);
        return getDataTable(commodityList);
    }

    /**
     *  批量入库模板下载
     * */
    @GetMapping("/warehouse/template")
    public void downloadTemplate(HttpServletResponse response) {
        try {
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("template.xlsx", "UTF-8"));
            ExcelUtil<Commodity> excelUtil = new ExcelUtil<>(Commodity.class);
            excelUtil.init(Collections.emptyList(),"sheet1", Excel.Type.EXPORT);
            excelUtil.exportExcel(response.getOutputStream());
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }


    /**
     * 商品批量入库
     * */
    @PostMapping("/warehouse/export")
    @ApiOperation(value = "商品批量入库", httpMethod = "POST",response = CommodityExportErrorVo.class)
    public AjaxResult warehouseExport(@RequestPart MultipartFile file){
        if (file == null || file.isEmpty()) {
            return AjaxResult.error("上传的文件不能为空");
        }
        List<Commodity> commodityList = new ArrayList<>();
        try {
            ExcelUtil<Commodity> util = new ExcelUtil<Commodity>(Commodity.class);
            commodityList = util.importExcel(file.getInputStream());
        } catch (Exception e){
            return AjaxResult.error("商品批量入库,文件上传失败");
        }
        List<CommodityExportErrorVo> commodityExportErrorVos = warehouseService.exportAddWarehouseList(commodityList);

        if(CollectionUtils.isNotEmpty(commodityExportErrorVos)){
            return AjaxResult.error("存在批量入库失败商品",commodityExportErrorVos);
        }
        return AjaxResult.success();
    }
}
